package com.shopping.controller;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.rmi.server.UID;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.shopping.model.Admins;
import com.shopping.model.Goods;
import com.shopping.model.Tops;
import com.shopping.model.Types;
import com.shopping.model.Users;
import com.shopping.service.ITopsService;
import com.shopping.service.OrdersService;
import com.shopping.service.impl.AdminsServiceImpl;
import com.shopping.service.impl.GoodsServiceImpl;
import com.shopping.service.impl.ItemServiceImpl;
import com.shopping.service.impl.TypesServiceImpl;
import com.shopping.service.impl.UsersServiceImpl;
import com.shopping.utils.PageUtil;

/**
 * 
 * 管理员控制器
 */
@Controller
@RequestMapping("/admin")
public class AdminController {
	@Autowired
	AdminsServiceImpl adminService;

	@Autowired
	private OrdersService ordersService;
	@Autowired
	GoodsServiceImpl goodsService;
	@Autowired
	ItemServiceImpl itemsService;
	@Autowired
	TypesServiceImpl typesService;
	@Autowired
	UsersServiceImpl usersService;
	@Autowired
	private ITopsService topsService;

	/**
	 * 登录
	 */
	@RequestMapping("/login")
	public String logins(String username, String password, HttpSession session) {
		System.out.println("username:" + username + ",password" + password);
		Admins admins = adminService.login(username, password);
		if (admins != null) {
			session.setAttribute("admins", admins);
			return "index.jsp";
		} else {
			return "login.jsp";
		}
	}

	@RequestMapping("/findAllTops")
	public String findAllTops(Model model) {
		List<Tops> tops = topsService.findAll();
		for (Tops top : tops) {
			System.out.println("推荐信息" + top.toString());
		}

		model.addAttribute("typeList", tops);
		return "type_list.jsp";
	}

	/**
	 * 退出登录
	 */
	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		session.removeAttribute("admins");
		return "login.jsp";

	}

	/**
	 * 分页查询管理员信息
	 */
	@RequestMapping("/adminList")

	public String findadmin(Model model, Integer page) {
		// 每页10条数据
		int pageSize = 5;
		// 获取总数据
		int count = adminService.adminCount();
		// 计算总页数
		int pages = count / pageSize;
		// 如果有多出的数据那么多加一页
		if (count % pageSize != 0) {
			pages += 1;
		}

		// 第几页
		int curPage = 1;
		if (page != null) {
			curPage = page;
		}

		// 超出范围
		if (curPage > pages) {
			curPage = pages;
		}
		if (curPage < 1) {
			curPage = 1;
		}
		List<Admins> list = adminService.findAdmins(pageSize, curPage);
		model.addAttribute("adminList", list);
		model.addAttribute("curPage", curPage);
		model.addAttribute("pages", pages);
		model.addAttribute("count", count);
		return "admin_list.jsp";
	}

	/**
	 * 商品管理页
	 * @param type 分页查询
	 * @param curPage	第几页
	 * @param model
	 * @return good_list.jsp
	 */
	@RequestMapping("/goodList")
	public String findAllGoods(Integer type,Integer page,Model model) {
		List<Goods> goods = new ArrayList<Goods>();
		int pageSize = 10;
		int curPage = 1;
		int goodSize = 0;
		int pages = 0;
		//分页查询商品
		if(type==null) {
			
			if(page!=null) {
				curPage = page;
			}
			int offset = (curPage-1)*pageSize;
			goods = goodsService.findByPage(offset, pageSize);
			goodSize = goodsService.findAll().size();
			pages = goodSize/pageSize;
			if (goodSize % pages!= 0) {
				pages += 1;
			}
			for (Goods good : goods) {
				//加入分类
				good.setType(typesService.selByIdTypes(good.getTypeId()));
				//查询是否是推荐商品
				Tops top= topsService.findTopsByGoodId(good.getId());
				if(top==null) {
					good.setTop(false);
				}else {
					good.setTop(true);
				}
				//遍历
				//System.out.println(good.toString());
				//System.out.println(good.getType().getName());
			}
		}else {
			List<Tops> tops ;
			//根据type查询推荐商品
			if(page!=null) {
				curPage = page;
			}

			int offset = (curPage-1)*pageSize;
			tops = topsService.findByPage(offset, pageSize);
			goodSize = topsService.findAll().size();
			pages = goodSize/pageSize;
			if (goodSize % pages!= 0) {
				pages += 1;
			}
			for (Tops top : tops) {
				Goods good = goodsService.findById(top.getGoodId());
				good.setTop(true);
				good.setType(typesService.selByIdTypes(good.getTypeId()));
				goods.add(good);
			}
		}
		model.addAttribute("count", goodSize);
		model.addAttribute("curPage",curPage);
		model.addAttribute("pages", pages);
		model.addAttribute("goodList", goods);
		model.addAttribute("pages", pages);
		return "good_list.jsp";
	}

	/**
	 * 根据id查询商品信息，跳转到修改页面
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/goodEdit")
	public String editGoods(Integer id, Model model) {
		Goods good = goodsService.findById(id);
		good.setType(typesService.selByIdTypes(good.getTypeId()));
		List<Types> typeList = typesService.selAllTypes();
		model.addAttribute("good", good);
		model.addAttribute("typeList", typeList);
		return "good_edit.jsp";
	}

	/**
	 * 添加管理员
	 */
	@RequestMapping("/adminSave")

	public String addAdmins(Admins admin) {
//		System.out.println("进来了");
		int num = adminService.insertAdmin(admin);
		return "redirect:adminList";
	}

	@RequestMapping("/goodUpdate")
	public String goodsUpdateById(Goods entity ,MultipartFile file) {
		String name = file.getOriginalFilename();// 文件名
		String url = "F:\\CodeWorkSpace\\eclipseWorkspace\\实训\\GroupFive\\WebContent\\upload\\";// 存储文件德绝对路径
		int lastIndex = name.lastIndexOf(".");// 获取文件尾缀下标
		String last = name.substring(lastIndex);// 获取文件尾缀
		String uid = UUID.randomUUID().toString();// 随机生成一串字符
		uid = uid.replace("-", "");
		name = "/" + uid + last;
		System.out.println("文件名=" + name);
		System.out.println("文件" + new File(url + name).getPath());
		try {
			file.transferTo(new File(url + name));
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		name = "../upload" + name;
		entity.setCover(name);
		int ret = goodsService.edit(entity);
		System.out.println(ret > 0 ? "修改成功" : "修改失败");
		return "redirect:findAllGoods";
	}

	/**
	 * 删除商品
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/goodDelete")
	public String removeGoodsById(Integer id) {
		goodsService.deleteById(id);
		return "redirect:findAllGoods";
	}

	/**
	 * 跳转到添加商品页面
	 * 
	 * @return
	 */
	@RequestMapping("/goodAdd")
	public String toAddGood(Model model) {
		List<Types> typeList = typesService.selAllTypes();
		model.addAttribute("typeList", typeList);
		return "good_add.jsp";
	}

	/**
	 * 添加商品
	 * 
	 * @param goods
	 * @return
	 */
	@RequestMapping("/goodSave")
	public String addGoods(Goods goods, MultipartFile file, HttpSession session, HttpServletRequest request) {
		String name = file.getOriginalFilename();// 文件名
		String url = "F:\\CodeWorkSpace\\eclipseWorkspace\\实训\\GroupFive\\WebContent\\upload\\";// 存储文件德绝对路径
		int lastIndex = name.lastIndexOf(".");// 获取文件尾缀下标
		String last = name.substring(lastIndex);// 获取文件尾缀
		String uid = UUID.randomUUID().toString();// 随机生成一串字符
		uid = uid.replace("-", "");
		name = "/" + uid + last;
		System.out.println("文件名=" + name);
		System.out.println("文件" + new File(url + name).getPath());
		try {
			file.transferTo(new File(url + name));
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		name = "../upload" + name;
		goods.setCover(name);
		System.out.println(goods.toString());
		// goodsService.add(goods);
		return "redirect:goodList";
	}

	/**
	 * 添加今日推荐
	 * 
	 * @param top
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/topSave")
	public void addTops(Tops top, HttpServletResponse resp) throws IOException {

		resp.getWriter().print((topsService.add(top) == null) ? "ok" : "error");

	}

	/**
	 * 移出今日推荐
	 * 
	 * @param tId
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("topDelete")
	public void removeTopsById(Integer goodId, HttpServletResponse resp) throws IOException {
		System.out.println(goodId);
		int ret = topsService.deleteByGoodId(goodId);
		System.out.println(ret);
		if (ret > 0) {
			resp.getWriter().print("ok");
		} else {
			resp.getWriter().print("error");
		}
	}

	/**
	 * 重置管理员密码
	 */
	@RequestMapping("/selByIdAdmin")
	public String selByIdAdmin(Integer id, Model model) {
		Admins ad = adminService.selByIdAdmin(id);
		model.addAttribute("param", ad);
		return "admin_reset.jsp";

	}

	@RequestMapping("/adminReset")
	public String redAdmin(String password, Integer id) {
		int num = adminService.redAdmin(password, id);
		return "redirect:adminList";

	}

	/**
	 * 删除管理员
	 */
	@RequestMapping("/adminDelete")
	public String delAdmin(Integer id) {
		int num = adminService.delAdmin(id);
		return "redirect:adminList";

	}

	/**
	 * 查询所有类目
	 */
	@RequestMapping("/typeList")
	public String typeList(Model model) {
		List<Types> list = typesService.selAllTypes();
		model.addAttribute("typeList", list);
		return "type_list.jsp";

	}

	/**
	 * 添加类目
	 */
	@RequestMapping("/typeSave")
	public String addTypes(Types type) {
		int num = typesService.addTypes(type);
		return "redirect:typeList";

	}

	/**
	 * 修改类目
	 */
	@RequestMapping("/typeEdit")
	public String selByIdType(Integer id, Model model) {
		Types ty = typesService.selByIdTypes(id);
		model.addAttribute("type", ty);
		return "type_edit.jsp";

	}

	@RequestMapping("/typeUpdate")
	public String editTypes(Types type) {
		int num = typesService.editTypes(type);
		return "redirect:typeList";

	}

	/**
	 * 删除类目
	 */
	@RequestMapping("/typeDelete")
	public String delType(Integer id) {
		int num = typesService.delType(id);
		return "redirect:typeList";
	}

	/**
	 * 分页查询客户信息
	 */
	@RequestMapping("/userList")
	public String selUsers(Integer page, Model model) {
		// 设置每页数据
		int uspage = 5;
		// 总数据数量
		int userCount = usersService.selUserscount();
		// 总页数
		int ye = userCount / uspage;
		// 判断是否有多出的数据，如果有多加一页
		if (userCount % uspage != 0) {
			ye += 1;
		}
		// 第几页
		int cupage = 1;
		if (page != null) {
			cupage = page;
		}
		if (cupage < 1) {
			cupage = 1;
		}
		if (cupage > ye) {
			cupage = ye;
		}

		List<Users> list = usersService.selUser(cupage, uspage);
		model.addAttribute("userList", list);
		model.addAttribute("count", userCount);
		model.addAttribute("pages", ye);
		model.addAttribute("curPage", cupage);

		return "user_list.jsp";

	}

	/**
	 * 添加客户
	 */
	@RequestMapping("/userSave")
	public String addUsers(Users user) {
		int num = usersService.addUsers(user);
		return "redirect:userList";

	}

	/**
	 * 重置用户密码
	 */
	@RequestMapping("/user_reset")
	public String selByIdUser(Integer id, Model model) {
		Users user = usersService.selByIdUser(id);
		model.addAttribute("param", user);
		return "user_reset.jsp";

	}

	@RequestMapping("/userReset")
	public String editUserPwd(Integer password, Integer id) {
		int num = usersService.editUserPwd(password, id);
		return "redirect:userList";

	}

	/**
	 * 修改客户信息
	 */
	@RequestMapping("/userEdit")
	public String selByidUser(Integer id, Model model) {
		Users user = usersService.selByIdUser(id);
		model.addAttribute("user", user);
		return "user_edit.jsp";

	}

	@RequestMapping("/userUpdate")
	public String editUsers(Users user) {
		int num = usersService.editUsers(user);
		return "redirect:userList";

	}

	/**
	 * 删除客户
	 */
	@RequestMapping("/userDelete")
	public String delUsers(Integer id) {
		int num = usersService.delUsers(id);
		return "redirect:userList";

	}

	
	@RequestMapping("/orderList")
	public String orderList(HttpServletRequest request, Model m, 
			@RequestParam(required = false, defaultValue = "0") byte status,
			@RequestParam(required = false, defaultValue = "1") int page,
			@RequestParam(required = false, defaultValue = "5") int size) {
		//分页查询订单，status=0:全部订单；status=1：未付款订单；status=2：
		//已付款订单；status=3：配送中订单；status=4：已完成订单。
		m.addAttribute("falg", 3);
		//根据状态，高亮选中查询选项
		m.addAttribute("status", status);
		//分页查询数据
		m.addAttribute("orderList", ordersService.orderList(status, page, size));
		//分页HTML代码
		m.addAttribute("pageTool", PageUtil.getPageTool(request, ordersService.getCountsByStatus(status), page, size));
		return "order_list.jsp";
	}
	
	
	@RequestMapping("/orderUpdate")
	public String orderUpdate(int id, byte status) {
		//修改订单的状态后，重新分页查询所有订单
		ordersService.orderUpdate(id, status);
		return "redirect:orderList";
	}
	
	@RequestMapping("/orderDelete")
	public String orderDelete(int id) {
		//删除订单后，重新分页查询所有订单
		ordersService.orderDelete(id);
		return "redirect:orderList";
	}
}
